package cn.yqm.modules.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.yqm.common.exception.YqmException;
import cn.yqm.dto.YqmSysRoleDto;
import cn.yqm.entity.YqmSysRole;
import cn.yqm.req.YqmSysRoleReq;
import cn.yqm.service.IYqmSysRoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 角色
 *
 * @author weiximei
 * @domain www.yqmshop.cn
 * @since 2023/8/6
 */

@AllArgsConstructor
@Service
public class RoleService {

    private final IYqmSysRoleService iYqmSysRoleService;

    /**
     * 分页查询
     *
     * @param req
     * @return
     */
    public IPage<YqmSysRoleDto> page(YqmSysRoleReq req) {
        IPage<YqmSysRole> page = new Page<>(req.getPage(), req.getPageSize());
        IPage pageList = iYqmSysRoleService.page(page, iYqmSysRoleService.getQuery(req));
        pageList.setRecords(BeanUtil.copyToList(pageList.getRecords(), YqmSysRoleDto.class));
        return pageList;
    }

    /**
     * 保存/或修改
     *
     * @param req
     * @return
     */
    public YqmSysRoleDto save(YqmSysRoleReq req) {
        YqmSysRole yqmSysRole = new YqmSysRole();
        if (Objects.nonNull(req.getRoleId())) {
            yqmSysRole = iYqmSysRoleService.getById(req.getRoleId());
        }

        BeanUtil.copyProperties(req, yqmSysRole);
        iYqmSysRoleService.saveOrUpdate(yqmSysRole);

        YqmSysRoleDto sysRoleDto = YqmSysRoleDto.builder().build();
        BeanUtil.copyProperties(yqmSysRole, sysRoleDto);
        return sysRoleDto;
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    public YqmSysRoleDto getById(String id) {
        YqmSysRole yqmSysRole = new YqmSysRole();
        if (StringUtils.isNotBlank(id)) {
            yqmSysRole = iYqmSysRoleService.getById(id);
        }

        YqmSysRoleDto sysRoleDto = YqmSysRoleDto.builder().build();
        BeanUtil.copyProperties(yqmSysRole, sysRoleDto);
        return sysRoleDto;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    public boolean delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new YqmException("数据不存在！请检查");
        }
        return iYqmSysRoleService.removeByIds(ids);
    }

    /**
     * 删除 - 根据 id
     *
     * @param id
     * @return
     */
    public boolean deleteById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new YqmException("数据不存在！请检查");
        }
        return iYqmSysRoleService.removeById(Long.valueOf(id));
    }


}
